﻿using System.Reflection;
using Volo.Abp.Validation;
using AbpVnext_Module.Validations;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using Volo.Abp.DependencyInjection;

namespace AbpVnext_Module.Validations
{
    /// <summary>
    /// 全局自定义 自动api控制器和手动控制器api验证
    /// </summary>
    //[Dependency(ServiceLifetime.Transient)]
    public class CustomObjectValidationContributor : IObjectValidationContributor   //自定义全局验证
    {
        public Task AddErrorsAsync(ObjectValidationContext context)
        {
            //throw new NotImplementedException();
            object result = context.ValidatingObject;
            //反射获取属性字段并校验属性值是否符合规范
            var type = result.GetType();
            PropertyInfo[] propertyInfos = type.GetProperties();
            foreach (PropertyInfo item in propertyInfos)
            {
                NamesAttribute namesAttribute = item.GetCustomAttribute<NamesAttribute>();
                if (namesAttribute != null)
                {
                    object val = item.GetValue(result);
                    //校验属性值必须含有123 （测试）
                    if (!val.ToString().Contains(namesAttribute.Value))
                    {
                        context.Errors.Add(new ValidationResult($"{item.Name}属性值必须含有123", new string[] { item.Name }));
                    }
                }
            }
            return Task.CompletedTask;
        }
    }
}
